from app.extensions import db
from app.models.model_mixin import BaseMixin


class Attachment(db.Model, BaseMixin):
    id = db.Column(db.Integer, primary_key=True)
    uid = db.Column(db.Integer, db.ForeignKey('article.id'), default=None)
    url = db.Column(db.String(255))

    article = db.relationship('Article', back_populates='attachments')

    def to_dict(self):
        return 'https://lsol-house-upload.oss-cn-hangzhou.aliyuncs.com/{}#{}'.format(self.url, self.id)

    @staticmethod
    def to_collection_dict(query, page, per_page=10):
        resources = query.paginate(page, per_page, False)
        data = {
            'items': [item.to_dict() for item in resources.items],
            '_meta': {
                'page': page,
                'per_page': per_page,
                'total_pages': resources.pages,
                'total_items': resources.total
            }
        }
        return data
